package my.sorter.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import com.sun.mail.imap.protocol.ID;
import com.sun.org.apache.xpath.internal.operations.Bool;
import my.sorter.bean.MyPageInfo;
import my.sorter.bean.StaffInfo;
import my.sorter.bean.filter.RoleInfo;
import my.sorter.bean.filter.StaffFilter;
import my.sorter.dao.model.Permission;
import my.sorter.dao.model.Role;
import my.sorter.dao.model.Staff;
import my.sorter.service.SecurityService;
import my.sorter.translator.out.MyMessage;
import my.sorter.utils.IdUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author zyf10
 */
@Controller
public class SecurityController {
    @Autowired
    private SecurityService securityService;

    /**
     * 登入系统
     *
     * @param staff
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(Staff staff) {
        Preconditions.checkNotNull(staff.getJobNumber());
        Preconditions.checkNotNull(staff.getPasswd());
        UsernamePasswordToken token = new UsernamePasswordToken(
                staff.getJobNumber().toString(),
                staff.getPasswd()
        );
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        return MyMessage.successMessage().addMessage("登入成功");
    }
    /**
     * 注册
     *
     * @param staff
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public Object register(Staff staff) {
        Preconditions.checkNotNull(staff.getJobNumber());
        Preconditions.checkNotNull(staff.getStaffName());
        Preconditions.checkNotNull(staff.getDepartment());
        Preconditions.checkNotNull(staff.getPasswd());
        Preconditions.checkNotNull(staff.getPost());
        staff.setActive(false);
        boolean flag = securityService.register(staff);
        return flag ? MyMessage.successMessage().addMessage("申请账户成功") : MyMessage.failMessage().addMessage("申请账户失败");
    }

    @RequiresPermissions("admin")
    @GetMapping("/security/get")
    @ResponseBody
    public Object getSecurityJson(@RequestParam(value = "job_number") Integer jobNumber) {
        JSONObject security = securityService.getSecurityJson(jobNumber);
        return MyMessage.successMessage().addMessage("获取员工权限信息成功").addData(security);
    }

    @RequiresPermissions("admin")
    @PostMapping("/security/update")
    @ResponseBody
    public Object updateSecurityJson(String securityString) {
        JSONObject securityJson = JSON.parseObject(securityString);
        boolean flag = securityService.updateSecurityJson(securityJson);
        return flag ? MyMessage.successMessage().addMessage("更新权限成功") : MyMessage.failMessage().addMessage("更新权限失败");
    }

    @RequiresPermissions("admin")
    @GetMapping("/security/full")
    @ResponseBody
    public Object getFullSecurityJson() {
        JSONObject security = securityService.getFullSecurityJson();
        return MyMessage.successMessage().addMessage("获取权限信息成功").addData(security);
    }


    @RequiresPermissions("admin")
    @GetMapping("/security/permission/get")
    @ResponseBody
    public Object getFullPermission(MyPageInfo myPageInfo, String permissionName) {
        /*
         * 第一个参数是第几页；第二个参数是每页显示条数。
         */
        PageHelper.startPage(myPageInfo.getCurrentPage(), myPageInfo.getPageSize());
        List<Permission> fullPermission = securityService.getPermission(permissionName);
        PageInfo pageInfo = new PageInfo(fullPermission);
        myPageInfo.setTotal((new Long(pageInfo.getTotal()).intValue()));
        myPageInfo.setTotalPage(pageInfo.getPages());
        return MyMessage.successMessage("获取所有权限信息成功", myPageInfo).addData(fullPermission);
    }

    @RequiresPermissions("admin")
    @PostMapping("/security/permission/delete")
    @ResponseBody
    public Object deletePermission(String permissionIds) {
        JSONArray idsArr = JSON.parseArray(permissionIds);
        List<String> ids = new ArrayList<>();
        for (Object id : idsArr.toArray()) {
            ids.add(id.toString());
        }
        boolean flag = securityService.deletePermission(ids);
        return flag ? MyMessage.successMessage("删除权限成功") : MyMessage.failMessage("删除权限失败");
    }

    @RequiresPermissions("admin")
    @PostMapping("/security/permission/createOrUpdate")
    @ResponseBody
    public Object createPermission(Permission permission) {
        Boolean flag = false;
        if (!ObjectUtils.isEmpty(permission)) {
            if (StringUtils.isEmpty(permission.getId())) {
                permission.setId(IdUtils.uuid());
                flag = securityService.createPermission(permission);
            } else {
                flag = securityService.updatePermission(permission);
            }
        }
        return flag ? MyMessage.successMessage("更改权限成功") : MyMessage.successMessage("更改权限失败");
    }

    /**
     * 查询用户
     *
     * @param myPageInfo
     * @param filter
     * @return
     */
    @RequiresPermissions("admin")
    @GetMapping("/security/staff/get")
    @ResponseBody
    public Object getStaff(MyPageInfo myPageInfo, StaffFilter filter) {
        if (ObjectUtils.isEmpty(filter.getActive())) {
            filter.setActive(true);
        }
        PageHelper.startPage(myPageInfo.getCurrentPage(), myPageInfo.getPageSize());
        List<Staff> staffs = securityService.getStaff(filter);
        PageInfo pageInfo = new PageInfo(staffs);
        myPageInfo.setTotal((new Long(pageInfo.getTotal()).intValue()));
        myPageInfo.setTotalPage(pageInfo.getPages());
        List<StaffInfo> staffInfos = Collections.synchronizedList(new ArrayList<>());
        for (Staff staff:staffs){
            StaffInfo staffInfo = new StaffInfo();
            staffInfo.setId(staff.getId());
            staffInfo.setJobNumber(staff.getJobNumber());
            staffInfo.setStaffName(staff.getStaffName());
            staffInfo.setDepartment(staff.getDepartment());
            staffInfo.setPost(staff.getPost());
            staffInfo.setActive(staff.getActive());
            staffInfo.setRole(securityService.getStaffRole(staff.getId()));
            if (!ObjectUtils.isEmpty(staffInfo.getRole())){
                staffInfo.setPermissions(securityService.getRolePermissions(staffInfo.getRole().getId()));
            }
            staffInfos.add(staffInfo);
        }
        return MyMessage.successMessage("获取所有权限信息成功", myPageInfo).addData(staffInfos);
    }

    /**
     * 激活账户
     * @param staffId
     * @return
     */
    @RequiresPermissions("admin")
    @PostMapping("/security/staff/active")
    @ResponseBody
    public Object activeStaff(String staffId){
        Boolean flag=securityService.activeStaff(staffId);
        return  flag?MyMessage.successMessage("激活账户成功"):MyMessage.failMessage("激活账户失败");
    }

    /**
     * 冻结账户
     * @param staffId
     * @return
     */
    @RequiresPermissions("admin")
    @PostMapping("/security/staff/frozen")
    @ResponseBody
    public Object frozenStaff(String staffId){
        Boolean flag=securityService.frozenStaff(staffId);
        return  flag?MyMessage.successMessage("冻结账户成功"):MyMessage.failMessage("冻结账户失败");
    }

    /**
     * 获取角色
     *
     * @param myPageInfo
     * @param roleName
     * @return
     */
    @RequiresPermissions("admin")
    @GetMapping("/security/role/get")
    @ResponseBody
    public Object getRole(MyPageInfo myPageInfo, String roleName) {
        List<RoleInfo> roleInfos=Collections.synchronizedList(new ArrayList<>());
        PageHelper.startPage(myPageInfo.getCurrentPage(), myPageInfo.getPageSize());
        List<Role> roles = securityService.getRole(roleName);
        PageInfo pageInfo = new PageInfo(roles);
        myPageInfo.setTotal((new Long(pageInfo.getTotal()).intValue()));
        myPageInfo.setTotalPage(pageInfo.getPages());
        for (Role role:roles){
            RoleInfo roleInfo=new RoleInfo();
            roleInfo.setId(role.getId());
            roleInfo.setRoleName(role.getRoleName());
            roleInfo.setRoleValue(role.getRoleValue());
            List<Permission> permissions=permissions=securityService.getRolePermissions(role.getId());
            roleInfo.setPermissions(permissions);
            roleInfos.add(roleInfo);
        }
        return MyMessage.successMessage("获取所有角色信息成功", myPageInfo).addData(roleInfos);
    }

    @PostMapping("/security/role/delete")
    @ResponseBody
    public Object deleteRole(String roleId){
        Boolean flag=securityService.deleteRole(roleId);
        return flag?MyMessage.successMessage("删除角色成功"):MyMessage.failMessage("删除角色失败");
    }
    /**
     * 更新用户的角色
     *
     * @param staffId
     * @param roleId
     * @return
     */
    @RequiresPermissions("admin")
    @PostMapping("/security/staffRole/update")
    @ResponseBody
    public Object updateStafRole(String staffId, String roleId) {
        Boolean flag = securityService.updateStaffRole(staffId, roleId);
        return flag ? MyMessage.successMessage("更新用户角色成功") : MyMessage.failMessage("更新用户角色失败");
    }

    /**
     * 更新角色的权限
     * @param role
     * @param pids
     * @return
     */
    @RequiresPermissions("admin")
    @PostMapping("/security/role/createOrUpdate")
    @ResponseBody
    public Object updateRolePermission(Role role, String pids) {
        Boolean flag;
        List<String> permissionIds = Collections.synchronizedList(new ArrayList<>());
        if (!ObjectUtils.isEmpty(pids)) {
            JSONArray pidArray = JSON.parseArray(pids);
            for (Object pid : pidArray.toArray()) {
                permissionIds.add(pid.toString());
            }
        }
        //判断是新增还是更新
        if (StringUtils.isEmpty(role.getId())){
            //新增
            String roleId = IdUtils.uuid();
            role.setId(roleId);
            Boolean f= securityService.createRole(role);
            if (f){
                flag = securityService.updateRolePermission(roleId, permissionIds);
            }else {
                flag=false;
            }
        }else {
            //更新
            flag = securityService.updateRolePermission(role.getId(), permissionIds);
        }
        return flag ? MyMessage.successMessage("更新角色的权限成功") : MyMessage.failMessage("更新角色的权限失败");
    }

}
